import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Tag, Modal, message, Form, Input, Select } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { BasicLayout } from '../../g-index/BasicLayout';
import { CustomTable } from '../../g-component/CustomTable';
import { User } from '../../g-types/user';
import { UserListApi } from './server';
import './index.less';

const { confirm } = Modal;
const { Option } = Select;

/**
 * 用户状态标签
 */
const UserStatusTag: React.FC<{ status?: number }> = ({ status }) => {
  if (status === 0) {
    return <Tag color="error">禁用</Tag>;
  }
  return <Tag color="success">启用</Tag>;
};

/**
 * 性别展示
 */
const GenderText: React.FC<{ gender?: number }> = ({ gender }) => {
  switch (gender) {
    case 1:
      return <span>男</span>;
    case 2:
      return <span>女</span>;
    default:
      return <span>未知</span>;
  }
};

/**
 * 用户列表页面
 */
export const UserList: React.FC = () => {
  // 用户列表数据
  const [userList, setUserList] = useState<User[]>([]);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 分页信息
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // 搜索关键字
  const [keyword, setKeyword] = useState<string>('');
  // 编辑用户的表单
  const [form] = Form.useForm();
  // 是否显示编辑Modal
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  // 当前编辑的用户
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  // 获取用户列表
  const fetchUserList = async (page = pagination.current, pageSize = pagination.pageSize, search = keyword) => {
    try {
      setLoading(true);
      const result = await UserListApi.getUserList({
        page,
        pageSize,
        keyword: search,
      });
      setUserList(result.list);
      setPagination({
        ...pagination,
        current: page,
        total: result.total,
      });
    } catch (error) {
      console.error('获取用户列表失败', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchUserList();
  }, []);

  // 处理表格变更
  const handleTableChange = (page: number, pageSize?: number) => {
    fetchUserList(page, pageSize);
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setKeyword(value);
    fetchUserList(1, pagination.pageSize, value);
  };

  // 处理添加/编辑用户
  const handleAddOrEditUser = () => {
    setCurrentUser(null);
    form.resetFields();
    setEditModalVisible(true);
  };

  // 处理编辑用户
  const handleEditUser = (user: User) => {
    setCurrentUser(user);
    form.setFieldsValue({
      username: user.username,
      nickname: user.nickname,
      email: user.email,
      phone: user.phone,
      gender: user.gender,
      department: user.department,
      position: user.position,
      role: user.role,
      status: user.status,
    });
    setEditModalVisible(true);
  };

  // 处理删除用户
  const handleDeleteUser = (user: User) => {
    confirm({
      title: '确定要删除此用户吗?',
      icon: <ExclamationCircleOutlined />,
      content: '删除后无法恢复',
      onOk: async () => {
        try {
          await UserListApi.deleteUser(user.id);
          message.success('删除成功');
          fetchUserList();
        } catch (error) {
          console.error('删除用户失败', error);
          message.error('删除用户失败');
        }
      },
    });
  };

  // 保存用户信息
  const handleSaveUser = async () => {
    try {
      const values = await form.validateFields();
      if (currentUser) {
        // 编辑用户
        await UserListApi.updateUser({
          id: currentUser.id,
          ...values,
        });
        message.success('更新用户成功');
      } else {
        // 新增用户
        await UserListApi.createUser(values);
        message.success('创建用户成功');
      }
      setEditModalVisible(false);
      fetchUserList();
    } catch (error) {
      console.error('保存用户失败', error);
      message.error('保存用户失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: (gender?: number) => <GenderText gender={gender} />,
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role?: string | string[]) => {
        if (!role) return '-';
        if (typeof role === 'string') return role;
        return role.join(', ');
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status?: number) => <UserStatusTag status={status} />,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: User) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditUser(record)}
          >
            编辑
          </Button>
          <Button 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDeleteUser(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 处理注销
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    window.location.href = '/login';
  };

  return (
    <BasicLayout onLogout={handleLogout}>
      <div className="user-list-container">
        <h2 className="page-title">用户管理</h2>

        <Card bordered={false}>
          <div className="table-operations">
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAddOrEditUser}
            >
              新增用户
            </Button>
          </div>
          
          <CustomTable<User>
            columns={columns}
            dataSource={userList}
            rowKey="id"
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              onChange: handleTableChange,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
            }}
            showSearch
            searchPlaceholder="搜索用户名、昵称、邮箱"
            onSearch={handleSearch}
            showRefresh
            onRefresh={() => fetchUserList()}
          />
        </Card>

        {/* 编辑用户弹窗 */}
        <Modal
          title={currentUser ? '编辑用户' : '新增用户'}
          visible={editModalVisible}
          onOk={handleSaveUser}
          onCancel={() => setEditModalVisible(false)}
          maskClosable={false}
          destroyOnClose
        >
          <Form
            form={form}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
            layout="horizontal"
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>
            
            {!currentUser && (
              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password placeholder="请输入密码" />
              </Form.Item>
            )}
            
            <Form.Item
              name="nickname"
              label="昵称"
            >
              <Input placeholder="请输入昵称" />
            </Form.Item>
            
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { type: 'email', message: '请输入有效的邮箱' }
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
            
            <Form.Item
              name="phone"
              label="手机号"
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
            
            <Form.Item
              name="gender"
              label="性别"
            >
              <Select placeholder="请选择性别">
                <Option value={0}>未知</Option>
                <Option value={1}>男</Option>
                <Option value={2}>女</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="department"
              label="部门"
            >
              <Input placeholder="请输入部门" />
            </Form.Item>
            
            <Form.Item
              name="position"
              label="职位"
            >
              <Input placeholder="请输入职位" />
            </Form.Item>
            
            <Form.Item
              name="role"
              label="角色"
            >
              <Select placeholder="请选择角色" mode="multiple">
                <Option value="admin">管理员</Option>
                <Option value="editor">编辑</Option>
                <Option value="viewer">访客</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="status"
              label="状态"
            >
              <Select placeholder="请选择状态">
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </BasicLayout>
  );
}; 